package com.joe.utils.db;

import com.joe.utils.PathUtils;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by joe on 2018/11/26
 */
public class ConnectionFactory {
    private static final Logger logger = LoggerFactory.getLogger(ConnectionFactory.class);

    private static Properties prop = new Properties();

    private static DataSource dataSource = null;

    public static void init() {
        try {
            prop.load(new FileInputStream(PathUtils.getRuntimeResourcePath() + "dbcp.properties"));
        } catch (IOException e) {
            logger.error("Error while load dbcp properties!", e);
        }

        try {
            dataSource = BasicDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Error while create data source!", e);
        }
    }

    /**
     * 获取新的连接
     */
    public static Connection getConnection() {
        Connection connection = null;
        if (dataSource == null) {
            init();
        }
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            logger.error("Get connection failed!", e);
        }
        return connection;
    }

}
